import * as Request from './request';
import Config from './config';
import Md5 from './md5';

function getHeaders(isVisitUser2) {
    const headers = {};

    if (isVisitUser2) headers.token = Config.token;
    else headers.token = window.token;

    headers['access-token'] = getAccessToken(Config.appId, headers.token);

    return headers
}

export function getCurrentTime() {
    let time = new Date().getTime();
    if (window.timeDiff) return time + window.timeDiff;

    const url = Config.apiServiceUrl + "Default/GetCurrentTime";
    Request.getRequest(url, null, (res) => {
        if (res.Data) res = res.Data;
        if (res.Time) {
            window.timeDiff = res.Time - time;
            time = res.Time;
        }
    }, null, false);
    return time;
}

function getAccessToken(appId, token) {
    const time = getCurrentTime();
    const md5str = Md5(appId + time + token);
    return window.btoa(appId + '@' + time + "@" + md5str);
}

export function getUserInfo(sid, mid) {
    const url = Config.apiServiceUrl + "VisitUser2/GetUserInfo";
    return promisePost(url, { VisitUser2: { Serial: sid, MeetingRoomId: mid } }, true);
}

export function getMeetingRoom() {
    const url = Config.apiServiceUrl + "MeetingRoom";
    return promiseGet(url);
}

function promiseGet(url, isVisitUser2) {
    return Request.promiseGetRequest(url, getHeaders(isVisitUser2)).then(res => {
        return Promise.resolve(getResponse(res));
    });
}

function promisePost(url, data, isVisitUser2) {
    return Request.promisePostRequest(url, getHeaders(isVisitUser2), data).then(res => {
        return Promise.resolve(getResponse(res));
    });
}

function getResponse(res) {
    const token = res.Token;
    if (res.Data) res = res.Data
    if (res.Ack) {
        if (res.Ack.IsSuccess) return res;
        else return { isSuccess: false, message: res.Ack.Message };
    } else if (res.Message || res.Exception) {
        return { isSuccess: false, message: res.Message || res.Exception };
    }
    if (token) res.Token = token;
    return res;
}